﻿angular.module('app.maildetail', [])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider
        .when('/maillist/maildetail/:mailId', {
            templateUrl: 'app/maillist/maildetail/maildetail.tpl.html',
            controller: 'maildetailCtrl',
            resolve: {
            }
        })
        .when('/maillist/maildetail',{
            templateUrl: 'app/maillist/maildetail/maildetail.tpl.html',
            controller: 'maildetailCtrl'
        });
    }])

    .controller('maildetailCtrl',
    ['$scope', 'baseDataProxy', 'modalService', 'mailTemplateProxy', '$interval', 'APPSETTING',
    'mailProxy', 'FileUploaderCommon', '$q', 'appFilesProxy', '$location', '$routeParams', 'mailInstanceService', 'collectorSoaProxy',
    '$anchorScroll', 'contactHistoryProxy', 'generateSOAProxy', 'uiGridConstants', 'cookieWatcherService',
    function ($scope, baseDataProxy, modalService, mailTemplateProxy, $interval, APPSETTING,
    mailProxy, FileUploaderCommon, $q, appFilesProxy, $location, $routeParams, mailInstanceService, collectorSoaProxy,
    $anchorScroll, contactHistoryProxy, generateSOAProxy, uiGridConstants, cookieWatcherService
    ) {
        
        $scope.custNums = "";
        $scope.arrCusts = [];
        $scope.hideGrid = true;
        $scope.inputClear = false;
        
        $scope.DateInt = function () {
            
            var date = new Date();
            //var str = "";
            //str += date.getFullYear();
            //str += date.getMonth() > 9 ? (date.getMonth() + 1).toString() : '0' + (date.getMonth() + 1);
            //str += date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate();
            var currentDate = new Date(date.getFullYear(), date.getMonth() + 1, date.getDate());
            //$scope.currentDate = parseInt(str);
            $scope.currentDate = currentDate;
            //alert(currentDate);
        }
        
        var mailId = $routeParams.mailId;
        $scope.invoiceList = {
            enableFiltering: true,
            columnDefs: [
                        {
                            field: 'invoiceNum', name: 'tmp', displayName: 'Invoice #', enableCellEdit: false, width: '100', pinnedLeft: true
                            , cellTemplate: '<div style="height:30px;vertical-align:middle"><a style="line-height:28px" ng-click="grid.appScope.openInvoiceH(row.entity.invoiceNum)">{{row.entity.invoiceNum}}</a></div>'
                            , filterHeaderTemplate: '<div class="ui-grid-filter-container" ><input class="form-control input-sm" ng-keyup="grid.appScope.findinvs()" id="invfilter"></div><div><a class="glyphicon glyphicon-remove" ng-show="grid.appScope.inputClear" ng-click="grid.appScope.removeInput()"></a></div>'
                                
                        },
                        { field: 'invoiceDate', enableCellEdit: false, displayName: 'Invoice Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },
                        { field: 'creditTrem', enableCellEdit: false, displayName: 'Credit Term', width: '100' },
                        { field: 'dueDate', enableCellEdit: false, displayName: 'Due Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '95' },
                        { field: 'customerNum', enableCellEdit: false, displayName: 'Customer #', width: '100' },
                        { field: 'customerName', enableCellEdit: false, displayName: 'Customer Name', width: '100' },
                        { field: 'legalEntity', enableCellEdit: false, displayName: 'Legal Entity', width: '100' },
                        { field: 'poNum', enableCellEdit: false, displayName: 'PO Num', width: '160' },
                        { field: 'soNum', enableCellEdit: false, displayName: 'SO Num', width: '122' },
                        { field: 'mstCustomer', enableCellEdit: false, displayName: 'RBO', width: '120' },
                        { field: 'currency', enableCellEdit: false, displayName: 'Currency', width: '90' },
                        {
                            field: 'balanceAmt', enableCellEdit: false, displayName: 'Outstanding Invoice Amount', cellFilter: 'number:2', type: 'number', width: '200'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (parseFloat(grid.getCellValue(row, col)) < 0) {
                                    return 'uigridred';
                                }
                            }
                        },
                        {
                            field: 'originalAmt', enableCellEdit: false, displayName: 'Original Invoice Amount', cellFilter: 'number:2', type: 'number', width: '200'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (parseFloat(grid.getCellValue(row, col)) < 0 ) {
                                    return 'uigridred';
                                }
                            }
                        },
                        {
                            name: 'daylate', displayName: 'Days Late', enableCellEdit: false,  width: '80',
                            cellTemplate: '<div style="height:30px;vertical-align:middle">{{grid.appScope.calDaysLate(row.entity)}}</div>'
                        },
                        {
                            name: 'states',enableCellEdit: false, displayName: 'Status', width: '80'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (grid.getCellValue(row, col) === '004004') {
                                    return 'uigridred';
                                }
                            }
                            , cellTemplate: '<div style="height:30px;vertical-align:middle">{{grid.appScope.getStatus(row.entity)}}</div>'
                            , filter: {
                                term: '',
                                type: uiGridConstants.filter.SELECT,
                                selectOptions: [
                                    { value: '004001', label: 'Open' },
                                    { value: '004002', label: 'PTP' },
                                    { value: '004003', label: 'Paid' },
                                    { value: '004004', label: 'Dispute' },
                                    { value: '004005', label: 'Cancelled' },
                                    { value: '004006', label: 'Uncollectable' },
                                    { value: '004007', label: 'WriteOff' },
                                    { value: '004008', label: 'PartialPay' },
                                    { value: '004010', label: 'Broken PTP' },
                                    { value: '004009', label: 'Closed' },
                                    { value: '004011', label: 'Hold' },
                                    { value: '004012', label: 'Payment' }]
                            }, cellFilter: 'mapStatus'
                        },
                        {
                            name: 'trackStates', enableCellEdit: false, displayName: 'Invoice Track', width: '100'
                            , cellTemplate: '<div style="height:30px;vertical-align:middle">{{grid.appScope.getTrackStatus(row.entity)}}</div>'
                            , filter: {
                                term: '',
                                type: uiGridConstants.filter.SELECT,
                                selectOptions: [
                                    { value: '001', label: 'SOA Sent' },
                                    { value: '002', label: 'Second Reminder Sent' },
                                    { value: '003', label: 'Final Reminder Sent' },
                                    { value: '004', label: 'Dispute' },
                                    { value: '005', label: 'PTP' },
                                    { value: '006', label: 'Payment Notice Received' },
                                    { value: '007', label: 'Broken PTP' },
                                    { value: '008', label: 'First Broken Sent' },
                                    { value: '009', label: 'Second Broken Sent' },
                                    { value: '011', label: 'Hold' },
                                    { value: '012', label: 'Agency Sent' },
                                    { value: '013', label: 'Write Off' },
                                    { value: '014', label: 'Paid' },
                                    { value: '015', label: 'Bad Debit' },
                                    { value: '016', label: 'Open' },
                                    { value: '017', label: 'Close' },
                                    { value: '018', label: 'Contra' },
                                    { value: '019', label: 'Breakdown' }
                                ]
                            }, cellFilter: 'mapTrack'
                        },
                        { field: 'ptpDate', enableCellEdit: false, displayName: 'PTP Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },
                        {
                            field: 'comments', name: 'tmp1', displayName: 'Invoice Memo', width: '120',
                            cellTemplate: '<div><a class="glyphicon glyphicon-pencil" ng-click="grid.appScope.editMemoShow(row.entity.id,row.entity.invoiceNum,row.entity.comments)"></a>'
+ '<label id="lbl{{row.entity.invoiceId}}" ng-mouseMove="grid.appScope.memoShow(row.entity.invoiceNum,row.entity.comments,$event)" ng-mouseOut="grid.appScope.memoHide()">{{row.entity.comments.substring(0,7)}}...</label></div>'
                        }
                        ],
                        onRegisterApi: function (gridApi) {
                            $scope.gridApi = gridApi;
                        }
        }


        $scope.view = function (mailId) {
            mailInstanceService.getViewMail(mailId).then(function (instance) {
                $scope.mailInstance = instance;

                if ($scope.mailInstance) {

                    //search CustomerNums & Name by mailId
                    //angular.forEach(instance.customerMails, function (customerMail) {
                    //    $scope.customerVisable += customerMail.customerNum;
                    //})
                    $scope.getCusByMailId();

                    if (instance.category == "Draft") {
                        $scope.hideReply = true;
                        $scope.hideForward = true;
                    }

                }
            });
        }

        $scope.isShowAssignCustomer = function () {
            if (!$scope.mailInstance) {
                return false;
            }
            if ($scope.mailInstance.category == "Sent"
            || $scope.mailInstance.category == "Processed") {
                return false;
            }

            return true;
        }

        $scope.showPending = function () {
            if (!$scope.mailInstance) {
                return false;
            }

            // Don't allow pending if mail in below status.
            if ($scope.mailInstance.category == "Draft"
                || $scope.mailInstance.category == "Sent"
                || $scope.mailInstance.category == "Processed"
                || $scope.mailInstance.category == "Pending") {
                return false;
            }

            if ($scope.mailInstance.title == "Mail Reply"
                || $scope.mailInstance.title == "Mail Forward") {
                return false;
            }

            return true;
        }

        $scope.showFinish = function () {
            if (!$scope.mailInstance) {
                return false;
            }

            // Don't allow pending if mail in below status.
            if ($scope.mailInstance.category == "Draft"
                || $scope.mailInstance.category == "Sent"
                || $scope.mailInstance.category == "Processed") {
                return false;
            }

            if ($scope.mailInstance.title == "Mail Reply"
                || $scope.mailInstance.title == "Mail Forward") {
                return false;
            }

            return true;
        }

        $scope.showReplyAndForward = function () {
            if (!$scope.mailInstance) {
                return false;
            }

            if ($scope.mailInstance.title == "Mail Reply"
                || $scope.mailInstance.title == "Mail Forward"
                || $scope.mailInstance.category == "Draft")
            {
                return false;
            }

            return true;
        }

        $scope.showGenerateSOA = function () {
            if (!$scope.mailInstance) {
                return false;
            }

            if ($scope.mailInstance.title == "Mail Reply"
                || $scope.mailInstance.title == "Mail Forward"
                || $scope.mailInstance.category == "Draft") {
                return true;
            }

            return false;
        }
        
        if (typeof mailId == "undefined") {
            mailInstanceService.getNewMail().then(function (instance) {
                $scope.mailInstance = instance;
            });
        } else {
            $scope.view(mailId);
        }
        $scope.DateInt();
        
        //remove customer from html & DB
        $scope.removeCus = function (cusNum) {
            //mailProxy.removeCus($scope.mailInstance.messageId, cusNum, function (res) {
            //    $scope.getCusts();
            //    $scope.readData();
            //}, function (error) {
            //    alert(error);
            //})
            var tempCusNum = cusNum + ',';
            var tempCustNums = $scope.custNums;
            if ($scope.custNums.indexOf(tempCusNum) >= 0) {
                $scope.custNums = $scope.custNums.replace(tempCusNum, "");
            } else {
                $scope.custNums = $scope.custNums.replace(cusNum, '');
            }
            $("#lbl" + cusNum).remove();

            //var arrcust = [];
            //var CustomerMails = [];
            //var arrcust = $scope.custNums.split(',');
            //angular.forEach(arrcust, function (cust) {
            //    CustomerMails.push({ MessageId: $scope.mailInstance.messageId, CustomerNum: cust });
            //    $scope.mailInstance.CustomerMails = CustomerMails;
            //})
            $scope.mailInstance.customerMails = $scope.refreshCus();
            $scope.readData();
        }

        $scope.mailDefaults = [];
        $scope.mailDefaults.showCancelBtn = true;
        $scope.modalInstance = {
            close: function (res, instance) {
                if (res == 'sent') {
                    alert('Sent successed.');
                    var watchingUrl = '';
                    if (typeof $routeParams.mailId == 'undefined') {
                        watchingUrl = '/maillist/maildetail/new';
                    } else {
                        watchingUrl = '/maillist/maildetail/' + mailId;
                    }

                    // write cookie to indicate the mail dialog closing.
                    cookieWatcherService().getWatchItem(watchingUrl).done();
                    // sent call back
                    window.close();
                }else {
                    $scope.view(mailId);
                }
            },
            dismiss: function () { }
        }

        $scope.reply = function () {
            mailInstanceService.getReplyMail(mailId).then(function (instance) {
                $scope.mailInstance = instance;
                $scope.mailInstance.title = "Mail Reply";
            });
        }

        $scope.forward = function () {
            mailInstanceService.getForwardMail(mailId).then(function (instance) {
                $scope.mailInstance = instance;
                $scope.mailInstance.title = "Mail Forward";
            });
        }

        $scope.finish = function () {
            mailProxy.updateMailCategory([mailId], 'Processed', function (res) {
                alert('Successfully set to processed.')
                $scope.mailInstance.category = 'Processed';
                cookieWatcherService().getWatchItem('/maillist/maildetail/' + mailId).done();
                window.close();
            }, function (error) {
                alert(error);
            })
        }

        $scope.pending = function () {
            mailProxy.updateMailCategory([mailId], 'Pending', function (res) {
                alert('Successfully set to Pending.')
                $scope.mailInstance.category = 'Pending';
            }, function (error) {
                alert(error);
            })
            $scope.readData();
        }

        $scope.AssignCustomer = function () {

            var modalDefaults = {
                templateUrl: 'app/maillist/contactcustomeredit/contactcustomer-edit.tpl.html',
                controller: 'contactCustomerEditCtrl',
                size: 'lg',
                resolve: {
                    messageId: function () { return $scope.mailInstance.messageId; },
                    customers: function () { return $scope.custNums; }
                },
                windowClass: 'modalDialog'
            };
            modalService.showModal(modalDefaults, {}).then(function (result) {
                //$scope.getCusts();
                if (result != null && result.length > 0) {
                    $scope.addCusts(result);
                    $scope.readData();
                }
            });

        }

        //get customer information by mailId
        $scope.getCusByMailId = function ()
        {
            var tempNums = "";
            mailProxy.query({ mailId: $routeParams.mailId }, function (customers) {
                $scope.customers = customers;

                angular.forEach($scope.customers, function (cust) {
                    tempNums += cust.customerNum + ',';
                })
                $scope.custNums = tempNums.substring(0, tempNums.length - 1);

                //angular.forEach($scope.customers, function (cust) {
                //    $scope.arrCusts.push(cust.customerNum);
                //})
                //$scope.custNums = $scope.arrCusts.join(',');
            })
        }

        //add assigned new customer
        $scope.addCusts = function (custs) {
            var tempNums = custs.join(',');
            if ($scope.custNums != "") {
                $scope.custNums += ',' + tempNums;
            } else {
                $scope.custNums += tempNums;
            }
            
            mailProxy.query({ mailCustNums: $scope.custNums }, function (customers) {
                $scope.customers = customers;
            })
            //angular.forEach(custs, function (cust) {
            //    $scope.mailInstance.CustomerMails.push({ MessageId: $scope.mailInstance.messageId, CustomerNum: cust });
            //})
            $scope.mailInstance.customerMails = $scope.refreshCus();
        }

        $scope.refreshCus = function () {
            var arrcust = [];
            var CustomerMails = [];
            var arrcust = $scope.custNums.split(',');
            angular.forEach(arrcust, function (cust) {
                CustomerMails.push({ MessageId: $scope.mailInstance.messageId, CustomerNum: cust });
            })
            if ($scope.mailInstance.title == "Mail View") {
                //数据库直接保存
                mailProxy.updateMailCus($scope.mailInstance.messageId, $scope.custNums, function (res) {
                    $scope.getCusts();
                    $scope.readData();
                }, function (error) {
                    alert(error);
                })
            }
            return CustomerMails;
        }

        //
        $scope.getCusts = function () {
            //var tempNums = "";
            //mailProxy.query({ mailCustNums: $scope.custNums }, function (customers) {
            //    $scope.customers = customers;

            //    angular.forEach($scope.customers, function (cust) {
            //        tempNums += cust.customerNum + ',';
            //    })
            //    $scope.custNums = tempNums.substring(0, tempNums.length - 1);
            //})
        }

        //refresh data if invoicelist is show
        $scope.readData = function () {
            if (!$scope.hideGrid) {
                $scope.getInvoice();
                
                //$window.location.hash = "#divInvoice";
            }
            //$scope.goto();
        }


        $scope.goto = function () {
            $location.hash('divInvoice');
            $anchorScroll();
        }

        //read invoice data
        $scope.getInvoice = function () {
            if ($scope.custNums != "") {
                //get invoiceList by customerNum
                mailProxy.query({ mailCustNumsForInv: $scope.custNums }, function (invoices) {
                    $scope.invoiceList.data = invoices
                })
            }
        }

        $scope.getInvoiceByInput = function (inputs) {
            if (inputs != "") {
                $scope.inputClear = true;
                //get invoiceList by customerNum and input nums
                mailProxy.query({ mailCustNumsForInv: $scope.custNums, inputNums: inputs }, function (invoices) {
                    $scope.invoiceList.data = invoices
                })
                
            } else {
                $scope.inputClear = false;
                $scope.getInvoice();
                
            }
        }

        //##########################
        //change invoice status
        //##########################
        $scope.changetab = function (type) {
            //get selected invoiceIds
            $scope.inv = [];

            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    $scope.inv.push(rowItem.id);

                }
            });

            if ($scope.inv == "" || $scope.inv == null) {
                alert("Please choose 1 invoice at least .")
                return;
            }

            if (type == "dispute") {

                var relatedMail = "";
                relatedMail = $scope.mailInstance.from + "  " + $scope.mailInstance.subject + " " + $scope.mailInstance.createTime.replace("T", " ");

                contactHistoryProxy.queryObject({ type: 'dispute' }, function (disInvInstance) {
                    disInvInstance["title"] = "Dispute Reason";
                    var modalDefaults = {
                        templateUrl: 'app/common/contactdetail/contact-dispute.tpl.html',
                        controller: 'contactDisputeCtrl',
                        size: 'lg',
                        resolve: {
                            disInvInstance: function () { return disInvInstance; },
                            custnum: function () { return ""; },
                            invoiceIds: function () { return $scope.inv; },
                            contactId: function () { return $scope.mailInstance.messageId; },
                            relatedEmail: function () { return relatedMail; },
                            contactPerson: function () { return $scope.mailInstance.to; }
                        },
                        windowClass: 'modalDialog'
                    };
                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        if (result == "submit") {
                            $scope.readData();
                        }
                    });
                });
            } else if (type == "ptp") {
                $scope.inv = [];

                angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {

                    if (rowItem.id != 0) {
                        $scope.inv.push(rowItem.id);
                    }
                });

                if ($scope.inv == "" || $scope.inv == null) {
                    alert("Please choose 1 invoice at least .")
                    return;
                }

                var relatedMail = "";
                relatedMail = $scope.mailInstance.from + "  " + $scope.mailInstance.subject + " " + $scope.mailInstance.createTime.replace("T", " ");

                var modalDefaults = {
                    templateUrl: 'app/common/contactdetail/contact-ptp.tpl.html',
                    controller: 'contactPtpCtrl',
                    size: 'lg',
                    resolve: {
                        custnum: function () {
                            return "";
                        },
                        invoiceIds: function () {
                            return $scope.inv;
                        },
                        contactId: function () {
                            return $scope.mailInstance.messageId;
                        },
                        relatedEmail: function () {
                            return relatedMail;
                        },
                        contactPerson: function () {
                            return $scope.mailInstance.to;
                        }
                    },
                    windowClass: 'modalDialog'
                };
                modalService.showModal(modalDefaults, {}).then(function (result) {
                    if (result[0] == "submit") {
                        $scope.readData();
                    }
                });
            } else if (type == "notice") {
                $scope.inv = [];

                angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {

                    if (rowItem.id != 0) {
                        $scope.inv.push(rowItem.id);
                    }
                });

                if ($scope.inv == "" || $scope.inv == null) {
                    alert("Please choose 1 invoice at least .")
                    return;
                }

                var relatedMail = "";
                relatedMail = $scope.mailInstance.from + "  " + $scope.mailInstance.subject + " " + $scope.mailInstance.createTime.replace("T", " ");

                var modalDefaults = {
                    templateUrl: 'app/common/contactdetail/contact-notice.tpl.html',
                    controller: 'contactNoticeCtrl',
                    size: 'lg',
                    resolve: {
                        custnum: function () {
                            return "";
                        },
                        invoiceIds: function () {
                            return $scope.inv;
                        },
                        contactId: function () {
                            return $scope.mailInstance.messageId;
                        },
                        relatedEmail: function () {
                            return relatedMail;
                        },
                        contactPerson: function () {
                            return $scope.mailInstance.to;
                        }
                    },
                    windowClass: 'modalDialog'
                };
                modalService.showModal(modalDefaults, {}).then(function (result) {
                    if (result[0] == "submit") {
                        $scope.readData();
                    }
                });
            }
        }


        //##########################
        //invoice memo edit
        //##########################
        //********************** edit one memo //**********************s
        $scope.editMemoShow = function (invoiceId, invoiceNum, memo) {
            if (invoiceId != 0) {
                $scope.selectText = memo;
                var h = document.documentElement.clientHeight;
                var w = document.documentElement.clientWidth;
                var content = document.getElementById('boxEdit');
                var contentWidth = $('#boxEdit').css('width').replace('px', '');
                var contentHeight = $('#boxEdit').css('height').replace('px', '');
                var stop = self.pageYOffset;
                var sleft = self.pageXOffset;
                var left = w / 2 - contentWidth / 2 + sleft;
                var top = h / 2 - contentHeight / 2 + stop;
                $('#boxEdit').css({ 'left': left + 'px', 'top': top + 'px' });
                $('#txtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 100 + 'px' });
                var str = '';
                var str1 = '';
                str = 'Invoice :"' + invoiceNum + '" Memo : ';
                str1 = memo;
                $("#hiddenInvId").val(invoiceId);
                $("#lblBoxTitle").html(str);
                $("#boxEdit").show();
            }
        }

        $scope.editMemoSave = function () {
            var list = [];
            var invoiceId = $("#hiddenInvId").val();
            var memo = $("#txtBox").val();
            list.push('2');
            list.push(invoiceId);
            list.push(memo);
            collectorSoaProxy.savecommon(list, function () {
                $scope.saveBack(invoiceId, memo);
                $scope.editMemoClose();
            });
        }

        $scope.saveBack = function (invoiceId, memo) {

            angular.forEach($scope.gridApi.grid.rows, function (rowItem) {
                if (rowItem.entity.id == invoiceId) {
                    rowItem.entity.comments = memo;
                }
            });

        }

        $scope.editMemoClose = function () {
            $("#boxEdit").hide();
        }
        //********************** edit one memo //**********************e

        //******************************* edit batch memo *******************************s
        $scope.batcheditMemoShow = function () {
            $scope.inv = [];
                angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                    if (rowItem.id != 0) {
                        $scope.inv.push(rowItem.id);
                    }
                });

            if ($scope.inv == "" || $scope.inv == null) {
                alert("Please choose 1 invoice at least .")
            } else {
                var h = document.documentElement.clientHeight;
                var w = document.documentElement.clientWidth;
                var content = document.getElementById('boxEdit');
                var contentWidth = $('#boxEdit').css('width').replace('px', '');
                var contentHeight = $('#boxEdit').css('height').replace('px', '');
                var stop = self.pageYOffset;
                var sleft = self.pageXOffset;
                var left = w / 2 - contentWidth / 2 + sleft;
                var top = h / 2 - contentHeight / 2 + stop;
                $('#boxEditBatch').css({ 'left': left + 'px', 'top': top + 'px' });
                $('#batchtxtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 120 + 'px' });
                var str = '';
                str = "All Selected Invoices' Memo Will Be Entirely Updated By Follow:"
                $("#batchhiddenInvId").val($scope.inv);
                $("#batchtxtBox").val("");
                $("#batchlblBoxTitle").html(str);
                $("#boxEditBatch").show();
            }
        }

        $scope.batcheditMemoSave = function () {
            var list = [];
            var invoiceIds = $("#batchhiddenInvId").val().toString();
            var memo = $("#batchtxtBox").val();
            list.push("5");
            list.push(invoiceIds);
            list.push(memo);
            collectorSoaProxy.savecommon(list, function () {
                $scope.batchsaveBack(memo);
                $scope.batcheditMemoClose();
            });
        }

        $scope.batchsaveBack = function (memo) {
                angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                    if (rowItem.id != 0) {
                        rowItem.comments = memo + '\r\n' + rowItem.comments;
                    }
                });
        }

        $scope.batcheditMemoClose = function () {
            $("#boxEditBatch").hide();
        }
        //******************************* edit batch memo *******************************e
        $scope.memoShow = function (invNum, memo, e) {
            $('#box').css({ 'left': e.pageX - 410 + 'px', 'top': e.pageY + 10 + 'px' });
            var str = '';
            str = 'Invoice :"' + invNum + '" Memo : <br>' + memo;
            $("#box").html(str);
            $("#box").show();

        }

        $scope.memoHide = function () {
            $("#box").hide();
        }

        //##########################
        //generate SOA attachment
        //##########################
        $scope.generateSoa = function () {
            $scope.inv = [];
            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    $scope.inv.push(rowItem.id);
                }
            });

            if ($scope.inv == "" || $scope.inv == null) {
                alert("Please choose 1 invoice at least .")
            } else {

                generateSOAProxy.geneateSoaByIds($scope.inv, 1, function (res) {
                    angular.forEach(res, function(att){
                        $scope.mailInstance.attachments.push(att);
                    });
                    
                    $scope.mailInstance.attachment += ("," + $scope.mailInstance.attachments.join(","));
                })
            }

        }

        //##########################
        //list params
        //##########################
        //******************************** days late ******************************
        $scope.calDaysLate = function (obj) {
            var aDate = obj.dueDate.toString().substring(0, 10).split('-');
            var date = new Date(aDate[0], aDate[1], aDate[2]);
            //date = date.getDate();
            //return (parseInt($scope.currentDate - obj.dueDate.toString().replace(/-/g, '').substring(0, 8)));
            return (($scope.currentDate - date) / 86400000);
        }

        //******************************** get status ******************************
        $scope.getStatus = function (obj) {
            var str = "";
            if (obj.states == '004001') {
                str = "Open";
            } else if (obj.states == '004002') {
                str = "PTP";
            } else if (obj.states == '004004') {
                str = "Dispute";
            } else if (obj.states == '004008') {
                str = "PartialPay";
            } else if (obj.states == '004010') {
                str = "Broken PTP";
            } else if (obj.states == '004011') {
                str = "Hold";
            } else if (obj.states == '004012') {
                str = "Payment";
            } else if (obj.states == '004003') {
                str = "Paid";
            } else if (obj.states == '004005') {
                str = "Cancelled";
            } else if (obj.states == '004009') {
                str = "Closed";
            } else if (obj.states == '004006') {
                str = "Uncollectable";
            } else if (obj.states == '004007') {
                str = "WriteOff";
            }
            return str;
        }

        //******************************** get track status ******************************
        $scope.getTrackStatus = function (obj) {
            var str = "";
            if (obj.trackStates == '001') {
                str = "SOA Sent";
            } else if (obj.trackStates == '002') {
                str = "Second Reminder Sent";
            } else if (obj.trackStates == '003') {
                str = "Final Reminder Sent";
            } else if (obj.trackStates == '004') {
                str = "Dispute";
            } else if (obj.trackStates == '005') {
                str = "PTP";
            } else if (obj.trackStates == '006') {
                str = "Payment Notice Received";
            } else if (obj.trackStates == '007') {
                str = "Broken PTP";
            } else if (obj.trackStates == '008') {
                str = "First Broken Sent";
            } else if (obj.trackStates == '009') {
                str = "Second Broken Sent";
            } else if (obj.trackStates == '011') {
                str = "Hold";
            } else if (obj.trackStates == '012') {
                str = "Agency Sent";
            } else if (obj.trackStates == '013') {
                str = "Write Off";
            } else if (obj.trackStates == '014') {
                str = "Paid";
            } else if (obj.trackStates == '015') {
                str = "Bad Debit";
            } else if (obj.trackStates == '016') {
                str = "Open";
            } else if (obj.trackStates == '017') {
                str = "Close";
            } else if (obj.trackStates == '018') {
                str = "Contra";
            } else if (obj.trackStates == '019') {
                str = "Breakdown";
            }
            return str;
        }

        //*********************************** open invoice history *********************************
        $scope.openInvoiceH = function (inNum) {
            var modalDefaults = {
                templateUrl: 'app/soa/invhistory/invhistory.tpl.html',
                controller: 'invHisCL',
                size: 'lg',
                resolve: {
                    inNum: function () { return inNum; }
                }
                , windowClass: 'modalDialog'
            };

            modalService.showModal(modalDefaults, {}).then(function (result) {

            });

        }

        //********************
        $scope.findinvs = function () {
            $scope.getInvoiceByInput($("#invfilter").val());
            ////alert($("#invfilter").val());
            //$scope.colFilter.listTerm = $("#invfilter").val().split(',');
            ////$scope.colFilter.listTerm = [];

            ////filinvs.forEach(function (filinv) {
            ////    $scope.colFilter.listTerm.push(filinv);
            ////});

            //$scope.colFilter.term = $scope.colFilter.listTerm.join(',');
            //$scope.colFilter.condition = new RegExp($scope.colFilter.listTerm.join('|'));

            //if ($elm) {
            //    $elm.remove();
            //}


        }

        //********************
        $scope.removeInput = function () {
            $("#invfilter").val("");
            $scope.getInvoice();
            $scope.inputClear = false;
        }

    }])

.filter('mapStatus', function () {
    var typeHash = {
        '004001': 'Open',
        '004002': 'PTP',
        '004003': 'Paid',
        '004004': 'Dispute',
        '004005': 'Cancelled',
        '004006': 'Uncollectable',
        '004007': 'WriteOff',
        '004008': 'PartialPay',
        '004010': 'Broken PTP',
        '004009': 'Closed',
        '004011': 'Hold',
        '004012': 'Payment'

    };
    return function (input) {
        if (!input) {
            return '';
        } else {
            return typeHash[input];
        }
    };
})
.filter('mapTrack', function () {
    var typeHash = {
        '001': 'SOA Sent',
        '002': 'Second Reminder Sent',
        '003': 'Final Reminder Sent',
        '004': 'Dispute',
        '005': 'PTP',
        '006': 'Payment Notice Received',
        '007': 'Broken PTP',
        '008': 'First Broken Sent',
        '009': 'Second Broken Sent',
        '011': 'Hold',
        '012': 'Agency Sent',
        '013': 'Write Off',
        '014': 'Paid',
        '015': 'Bad Debit',
        '016': 'Open',
        '017': 'Close',
        '018': 'Contra',
        '019': 'Breakdown'
    };
    return function (input) {
        if (!input) {
            return '';
        } else {
            return typeHash[input];
        }
    };
});
